package com.pig4cloud.pig.village.job;

import com.alibaba.fastjson.JSON;
import com.pig4cloud.pig.village.api.entity.RewardEvent;
import com.pig4cloud.pig.village.api.entity.WelfareRule;
import com.pig4cloud.pig.village.reward.service.IRewardEventService;
import com.pig4cloud.pig.village.rules.service.IRuleService;
import com.pig4cloud.pig.village.welfare.service.IWelfareRuleService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

import static com.pig4cloud.pig.village.api.CommonConst.*;
import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;

/**
 * 由xxl-job-admin调度的任务
 *
 * @author limnray.li
 * @date 2021/8/3
 */
@Slf4j
@Component
public class JobHandler {

	@Resource
	private IWelfareRuleService welfareRuleService;
	@Resource
	private IRewardEventService rewardEventService;
	@Resource
	private IRuleService ruleService;

	@XxlJob("testJob")
	public ReturnT<String> testJob(String s) {
		log.info("/testJob  start once!!!");
		List<WelfareRule> rules = welfareRuleService.getAllRules();
		log.info("rules:{}", JSON.toJSONString(rules));
		return SUCCESS;
	}

	@XxlJob("monthJob")
	public ReturnT<String> monthJob() {
		//月度任务，月初执行一次，需要剔除生日任务
		log.info("/monthJob start at {}", LocalDateTime.now());
		//查询月度任务，保存为RewardEvent
		List<WelfareRule> rules = welfareRuleService.getMonthRules();
		List<RewardEvent> events = welfareRuleService.eventConvert(rules, "monthJob", TIME_DIMENSION_MONTH);
		//事件events中，任务的福利id字段（scheduleWelfareId）相同的，合并,取其一
		// 根据scheduleWelfareId属性去重
		events = events.stream().collect(
				Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RewardEvent::getScheduleWelfareId))), ArrayList::new)
		);
		//保存到event表中
		rewardEventService.saveBatch(events);
		//执行规则
		events.forEach(e -> ruleService.dealRuleByEvent(e));
		log.info("/monthJob finished");
		return SUCCESS;
	}

	@XxlJob("yearJob")
	public ReturnT<String> yearJob() {
		//年度任务，年末执行一次，需要剔除生日任务
		log.info("/yearJob start at {}", LocalDateTime.now());
		//查询年度任务
		List<WelfareRule> rules = welfareRuleService.getYearRules();
		List<RewardEvent> events = welfareRuleService.eventConvert(rules, "yearJob", TIME_DIMENSION_YEAR);
		//事件events中，任务的福利id字段（scheduleWelfareId）相同的，合并,取其一
		// 根据scheduleWelfareId属性去重
		events = events.stream().collect(
				Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RewardEvent::getScheduleWelfareId))), ArrayList::new)
		);
		//保存到event表中
		rewardEventService.saveBatch(events);
		//执行规则
		events.forEach(e -> ruleService.dealRuleByEvent(e));
		log.info("/yearJob finished");
		return SUCCESS;
	}

	@XxlJob("birthMonthJob")
	public ReturnT<String> birthMonthJob() {
		//生日任务：每个月初，找到当月过生日的人员，触发任务
		log.info("/birthMonthJob start at {}", LocalDateTime.now());
		//查询生日任务，保存为RewardEvent
		List<WelfareRule> rules = welfareRuleService.getBirthDayRules();
		// 生日任务，按照发放维度的话，那应该是年，即TIME_DIMENSION_YEAR
		// 定时任务的话，是按月执行，这可以在页面上配置执行方式
		List<RewardEvent> events = welfareRuleService.eventConvert(rules, JOB_BIRTHMONTH, TIME_DIMENSION_YEAR);
//		List<RewardEvent> events = welfareRuleService.eventConvert(rules, JOB_BIRTHMONTH, TIME_DIMENSION_MONTH);
		//事件events中，任务的福利id字段（scheduleWelfareId）相同的，合并,取其一
		// 根据scheduleWelfareId属性去重
		events = events.stream().collect(
				Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RewardEvent::getScheduleWelfareId))), ArrayList::new)
		);
		//保存到event表中
		rewardEventService.saveBatch(events);
		//执行规则
		events.forEach(e -> ruleService.dealRuleByEvent(e));
		log.info("/birthMonthJob finished");
		return SUCCESS;
	}

	@XxlJob("schoolJob")
	public ReturnT<String> schoolJob() {
		//录取院校任务，按次执行，需要剔除生日任务
		log.info("/schoolJob start at {}", LocalDateTime.now());
		//查询月度任务，保存为RewardEvent
		List<WelfareRule> rules = welfareRuleService.getSchoolRules();
		List<RewardEvent> events = welfareRuleService.eventConvert(rules, "schoolJob", TIME_DIMENSION_ONCE);
		//事件events中，任务的福利id字段（scheduleWelfareId）相同的，合并,取其一
		// 根据scheduleWelfareId属性去重
		events = events.stream().collect(
				Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(RewardEvent::getScheduleWelfareId))), ArrayList::new)
		);
		//保存到event表中
		rewardEventService.saveBatch(events);
		//执行规则
		events.forEach(e -> ruleService.dealRuleByEvent(e));
		log.info("/schoolJob finished");
		return SUCCESS;
	}
}